package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRegistService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


/*
* 用户对象解析器
* 将cookie中的token 值解析成userinfo 对象并注入到请求映射方法中
*
* */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {


    @Reference
    private IUserInfoRegistService userInfoRegistService;


    //明确需要注入参数对象的类型
    //如果为true, 表示支持该类型, 如果为false表示不支持该类型注入
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前请求对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String  token = CookieUtil.getToken(request);
        UserInfo userInfo = userInfoRegistService.getUserByToken(token);
        return userInfo;
    }
}
